package sg4c.frontend;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import sg4c.backend.BackendConnector;
import sg4c.frontend.command.GraphicsCommand;
import sg4c.protocol.CaptureInput;

import sg4c.protocol.TextInputProtocol;
import sg4c.protocol.TextOutputProtocol;

public class CapturingGraphicFrontend extends GraphicsFrontend {

    private final CaptureInput captureInput;

    public CapturingGraphicFrontend(String exepath, String captureFile) throws IOException {
        conn = new BackendConnector(exepath);
        captureInput = new CaptureInput(new TextInputProtocol(conn.in), new BufferedOutputStream(new FileOutputStream(captureFile)));
        backendInput = captureInput;
        backendOutput = new TextOutputProtocol(conn.out);
    }

    @Override
    public void stop() {
        super.stop();
        try {
            //doing capture
            captureInput.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    protected void prepareGraphicCommands() {
        try {
            captureInput.disable();
            List<GraphicsCommand> commands = recvCommands();
            captureInput.enable();

            captureInput.writeObject(commands);
            captureInput.flush();
            for (GraphicsCommand cmd : commands) {
                cmd.execute(context);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }
}
